package com.kwan.xframe.pay.paystrategy;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alipay.sdk.app.PayTask;
import com.kwan.xframe.pay.ALiPayResult;
import com.kwan.xframe.pay.EasyPay;
import com.kwan.xframe.pay.PayParams;

import java.util.Map;


/**
 * Author: michaelx
 * Create: 17-3-13.
 * <p>
 * Endcode: UTF-8
 * <p>
 * Blog:http://blog.csdn.net/xiong_it | https://xiong-it.github.io
 * github:https://github.com/xiong-it
 * <p>
 * Description: 支付宝策略.
 */

public class ALiPayStrategy extends BasePayStrategy {
	private static final int PAY_RESULT_MSG = 0;
	private  Handler mHandler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			Log.e("kwan", "handleMessage::");
			if (msg.what != PAY_RESULT_MSG) {
				return false;
			}
			//    ThreadManager.shutdown();
			ALiPayResult result = new ALiPayResult((Map<String, String>) msg.obj);

			// result.getResult().

			Log.e("kwan", "ALiPayResult::" + result.getResultStatus());

			switch (result.getResultStatus()) {
				case ALiPayResult.PAY_OK_STATUS:
					mOnPayResultListener.onPayCallBack(EasyPay.COMMON_PAY_OK);
					break;

				case ALiPayResult.PAY_CANCEL_STATUS:
					mOnPayResultListener.onPayCallBack(EasyPay.COMMON_USER_CACELED_ERR);
					break;

				case ALiPayResult.PAY_FAILED_STATUS:
					mOnPayResultListener.onPayCallBack(EasyPay.COMMON_PAY_ERR);
					break;

				case ALiPayResult.PAY_WAIT_CONFIRM_STATUS:
					mOnPayResultListener.onPayCallBack(EasyPay.ALI_PAY_WAIT_CONFIRM_ERR);
					break;

				case ALiPayResult.PAY_NET_ERR_STATUS:
					mOnPayResultListener.onPayCallBack(EasyPay.ALI_PAY_NET_ERR);
					break;

				case ALiPayResult.PAY_UNKNOWN_ERR_STATUS:
					mOnPayResultListener.onPayCallBack(EasyPay.ALI_PAY_UNKNOW_ERR);
					break;

				default:
					mOnPayResultListener.onPayCallBack(EasyPay.ALI_PAY_OTHER_ERR);
					break;
			}
			mHandler.removeCallbacksAndMessages(null);
			return false;
		}
	});


	public ALiPayStrategy(PayParams params, String prePayInfo, EasyPay.PayCallBack resultListener) {
		super(params, prePayInfo, resultListener);

	}

	@Override
	public void doPay() {
		Runnable payRun = new Runnable() {
			@Override
			public void run() {

				Log.e("kwan", "doPay");
				PayTask task = new PayTask(mPayParams.getActivity());
				// TODO 请根据自身需求解析mPrePayinfo，最终的字符串值应该为一连串key=value形式
				Map<String, String> result = task.payV2(mPrePayInfo, true);
				Log.e("kwan", result.toString());
				Message message = mHandler.obtainMessage();
				message.what = PAY_RESULT_MSG;
				message.obj = result;
				mHandler.sendMessage(message);
			}
		};

		new Thread(payRun).start();

		//  ThreadManager.execute(payRun);
	}
}
